#include "U2Win32EGLSupport.h"

#include "U2StringConverter.h"
#include "U2Win32EGLWindow.h"



U2EG_NAMESPACE_USING


U2Win32EGLSupport::U2Win32EGLSupport()
{
	//RECT windowRect;
	//GetClientRect(mNativeDisplay, &windowRect);
	mNativeDisplay = getNativeDisplay();
	mGLDisplay = getGLDisplay();

	// Video mode possibilities
	DEVMODE DevMode;
	DevMode.dmSize = sizeof(DEVMODE);
	for (DWORD i = 0; EnumDisplaySettings(NULL, i, &DevMode); ++i)
	{
		if (DevMode.dmBitsPerPel < 16)
			continue;

		mCurrentMode.first.first = DevMode.dmPelsWidth; 
		mCurrentMode.first.second = DevMode.dmPelsHeight; 
		mCurrentMode.second = 0;
		mOriginalMode = mCurrentMode;
		mVideoModes.push_back(mCurrentMode);
	}

	EGLConfig *glConfigs;
	int config, nConfigs = 0;

	glConfigs = chooseGLConfig(NULL, &nConfigs);

	for (config = 0; config < nConfigs; config++)
	{
		int caveat, samples;

		getGLConfigAttrib(glConfigs[config], EGL_CONFIG_CAVEAT, &caveat);

		if (caveat != EGL_SLOW_CONFIG)
		{
			getGLConfigAttrib(glConfigs[config], EGL_SAMPLES, &samples);
			mSampleLevels.push_back(U2StringConverter::toString(samples));
		}
	}

	free(glConfigs);

	removeDuplicates(mSampleLevels);


}

U2Win32EGLSupport::~U2Win32EGLSupport()
{

}

void U2Win32EGLSupport::switchMode( u2uint& width, u2uint& height, short& frequency )
{
	if (!mRandr)
		return;

	int size = 0;
	int newSize = -1;

	VideoModes::iterator mode;
	VideoModes::iterator end = mVideoModes.end();
	VideoMode *newMode = 0;

	for(mode = mVideoModes.begin(); mode != end; size++)
	{
		if (mode->first.first >= static_cast<int>(width) &&
			mode->first.second >= static_cast<int>(height))
		{
			if (!newMode ||
				mode->first.first < newMode->first.first ||
				mode->first.second < newMode->first.second)
			{
				newSize = size;
				newMode = &(*mode);
			}
		}

		VideoMode* lastMode = &(*mode);

		while (++mode != end && mode->first == lastMode->first)
		{
			if (lastMode == newMode && mode->second == frequency)
			{
				newMode = &(*mode);
			}
		}
	}

	//todo
}

//Moved to native from U2EGLSupport 
U2RenderWindow* U2Win32EGLSupport::newWindow(const U2String &name,
                                    unsigned int width, unsigned int height,
                                    bool fullScreen,
                                    const NameValuePairList *miscParams)
{
//        EGLWindow* window = createEGLWindow(this);

    U2Win32EGLWindow* window = U2_NEW U2Win32EGLWindow(this);
    window->create(name, width, height, fullScreen, miscParams);

    return window;
}

//Moved to native from U2EGLSupport
NativeDisplayType U2Win32EGLSupport::getNativeDisplay()
{
	return EGL_DEFAULT_DISPLAY; // TODO
}

//Win32EGLSupport::getGLDisplay sets up the native variable
//then calls U2EGLSupport::getGLDisplay
EGLDisplay U2Win32EGLSupport::getGLDisplay()
{
	if (!mGLDisplay)
	{
		mNativeDisplay = getNativeDisplay();
		return U2EGLSupport::getGLDisplay();
	}
	return mGLDisplay;
}

